package com.example.servlet;

import com.example.dao.UserDao;
import com.example.dao.UserDaoImpl;
import com.example.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String message = null;
        UserDao userDao = null;
        User user = null;

        try {
            userDao = new UserDaoImpl();
            user = new User();
            user.setUsername(username);
            user.setPassword(password);

            if (userDao.isUsernameExists(username)) {
                message = "<li style='color:red;'>该用户名已被占用，请换一个用户名</li>";
            } else {
                boolean success = userDao.registerUser(user);
                if (success) {
                    message = "<li style='color:green;'>注册成功！欢迎加入CNCS饰品分析系统</li>";
                } else {
                    message = "<li style='color:red;'>注册失败，请稍后再试</li>";
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
            message = "<li style='color:red;'>数据库错误：" + e.getMessage() + "</li>";
        }

        // 不管是否成功，都转发到 register.jsp 显示提示
        request.setAttribute("result", message);
        RequestDispatcher rd = request.getRequestDispatcher("/jsp/register.jsp");
        rd.forward(request, response);
    }
}

